package org.jmc.refmanager.web.wicket.behavior;

import org.apache.wicket.Component;
import org.apache.wicket.behavior.AbstractBehavior;
import org.apache.wicket.markup.ComponentTag;
import org.apache.wicket.markup.html.IHeaderContributor;
import org.apache.wicket.markup.html.IHeaderResponse;
import org.apache.wicket.markup.html.form.FormComponent;

public class DisableEnterKeyBehavior extends AbstractBehavior implements
		IHeaderContributor {
	private static final long serialVersionUID = 1L;

	private FormComponent<?> formComp;

	public void renderHead(IHeaderResponse response) {
		response.renderJavascript(
				"function ignoreEnterKey(event){return !(event.keyCode==13 || window.event.keyCode==13);}",
				"vcomDisableEnterKey");
	}

	@Override
	public final void bind(Component component) {
		if (component == null)
			throw new IllegalArgumentException(
					"Argument component must be not null");

		if (formComp != null)
			throw new IllegalStateException(
					"This behavior cannot be attached to multiple components; it is already attached to component "
							+ formComp
							+ ", but component "
							+ component
							+ " wants to be attached too");

		if (!(component instanceof FormComponent))
			throw new IllegalArgumentException(
					"This behavior can only be attached to a FormComponent.");

		formComp = (FormComponent) component;
	}

	@Override
	public final void onComponentTag(Component component, ComponentTag tag) {
		if (formComp.isEnabled() && formComp.isEnableAllowed()) {
			tag.put("onkeypress", "return ignoreEnterKey(event);");
		}
	}
}
